package org.ssmd3.controller;

import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
import org.ssmd3.pojo.News;
import org.ssmd3.pojo.NewsType;
import org.ssmd3.service.NewsService;
import org.ssmd3.service.NewsTypeService;
import org.ssmd3.util.PageTool;

import javax.annotation.Resource;
import javax.servlet.http.HttpSession;
import java.io.File;
import java.io.IOException;
import java.util.Date;
import java.util.List;

@Controller
@RequestMapping("/news")
public class NewsController {
    @Resource
    NewsTypeService newsTypeService;
    @Resource
    NewsService newsService;

    @RequestMapping("/save")
    public String save(Model model){
        List<NewsType> plist=newsTypeService.getAllNewsTypeList();
        model.addAttribute("plist",plist);
        return "/news/save";
    }

    @RequestMapping("/dosave")
    public String doSave(Model model, News news, HttpSession session,@RequestParam(value = "a_newsImg",required = false) MultipartFile file){
        //1.保存图片
        if (file!=null){
            String path=session.getServletContext().getRealPath("/statics/upload");
            String oldFileName=file.getOriginalFilename();
            int mIndex=oldFileName.lastIndexOf(".");
            String nextName=oldFileName.substring(mIndex+1);

                //新文件的文件名
                String fileName=new Date().getTime()+"_"+(int)(Math.random()*1000000)+"."+nextName;

                File file1=new File(path,fileName);
                if (!file1.exists()){
                    file1.mkdirs();
                }
                try {
                    file.transferTo(file1);
                    //上传成功
                } catch (IOException e) {
                    e.printStackTrace();
                }
                news.setNewsImg(fileName);
        }

        //2.新增新闻
        newsService.save(news);

        return "redirect:/news/save";
    }

    @RequestMapping("/list")
    public String list(Model model, News news){

        int totalRecordCount=newsService.getRecordCount(news);
        PageTool pageTool=new PageTool(totalRecordCount,news.getCurrPageNo());
        int starNum=pageTool.getStartRow();
        int pageSize=pageTool.getPageSize();
        news.setStarNum(starNum);
        news.setPageSize(pageSize);

        List<News> list=newsService.getNewsListByPage(news);
        List<NewsType> plist=newsTypeService.getAllNewsTypeList();

        model.addAttribute("list",list);
        model.addAttribute("plist",plist);
        model.addAttribute("news",news);
        model.addAttribute("pageTool",pageTool);

        model.addAttribute("prePages",pageTool.getPrePages());
        model.addAttribute("nextPages",pageTool.getNextPages());

        return "/news/list";
    }

    @RequestMapping("/dodelete")
    @ResponseBody
    public String doDelete(Model model,int id){

        try{
            if (newsService.delete(id)>0){
                return "1";
            }
        }catch (Exception e){
            return "0";
        }

        return "0";
    }

    @RequestMapping("/dodeleteall")
    @ResponseBody
    public String doDeleteAll(String ids){

        String[] idsArray=ids.split(",");

        try {
            newsService.deleteAll(idsArray);
            return "1";
        }catch(Exception e){
            e.printStackTrace();
            return "0";
        }
    }

    @RequestMapping("/update")
    public String update(Model model,Integer id){
        News news=newsService.getOneNews(id);

        List<NewsType> plist=newsTypeService.getAllNewsTypeList();
        model.addAttribute("plist",plist);
        model.addAttribute("news",news);

        return "/news/update";
    }

    @RequestMapping("/doupdate")
    public String doUpdate(Model model,News news,HttpSession session,@RequestParam(value = "a_newsImg",required = false) MultipartFile file){
        if (file!=null){
            String path=session.getServletContext().getRealPath("/statics/upload");
            String oldFileName=file.getOriginalFilename();
            int mIndex=oldFileName.lastIndexOf(".");
            String nextName=oldFileName.substring(mIndex+1);

            if(nextName.equals("jpg")
                    ||nextName.equals("png")
                    ||nextName.equals("gif")){

                //新文件的 文件名
                String fileName=new Date().getTime()+"_"+(int)(Math.random()*1000000);

                File file1=new File(path,fileName+"."+nextName);
                if(!file1.exists()){
                    file1.mkdirs();
                }

                try {
                    file.transferTo(file1);
                    //上传成功
                    news.setNewsImg(fileName+"."+nextName);

                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }

        //2.新增新闻
//        News news1=newsService.getOneNews(news.getId());
//        news.setNewsImg(news1.getNewsImg());
        newsService.update(news);

        return "redirect:/news/list";
    }

    @RequestMapping("/edit")
    @ResponseBody
    public String editNews(String title,Integer id){

        try {
            News news=newsService.getOneNews(id);
            news.setTitle(title);
            newsService.update(news);
            return "1";
        }catch (Exception e){
            e.printStackTrace();
        }

        return "0";
    }

}
